<template>
    <div
        style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; background-color: #f5f7fa; padding: 10px; border: 1px solid #e4e7ed; border-radius: 4px;">
        <span>修改医院</span>
        <el-button type="primary" @click="set">返回</el-button>
    </div>
    <div style="border: groove; border-width: 2px; height: 100%; width: 800px; margin-top: 20px;">
        <header style="margin-top: 30px;margin-left: 20px;margin-right: 20px;margin-bottom: 50px;">
            <el-form label-width="auto" style="max-width: 600px">
                <el-form-item label="医院名称">
                    <el-input v-model="hospdata.name" placeholder="请输入……" />
                </el-form-item>
                <el-form-item label="列表图">
                    <el-upload class="avatar-uploader" v-model="hospdata.hospitalImg"
                        action="http://localhost:5047/api/carousimg/CarousImg" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="hospdata.hospitalImg" :src="hospdata.hospitalImg" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="是否推荐">
                    <el-radio-group v-model="hospdata.isHospital">
                        <el-radio :value="false">是</el-radio>
                        <el-radio :value="true">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="医院人数">
                    <el-input v-model="hospdata.hospitalCount" placeholder="请输入……" />
                </el-form-item>
                <el-form-item label="科室数">
                    <el-input v-model="hospdata.hospitalCountTow" placeholder="请输入……" />
                </el-form-item>
                <el-form-item label="医院科室">

                </el-form-item>
                <div><el-transfer v-model="hospdata.departments" :data="data" :loading="loading" /></div>
                <el-form-item label="详细地址">
                    <el-input v-model="hospdata.hospitalAddTow" placeholder="请输入……" />
                </el-form-item>
                <el-form-item label="医院电话">
                    <el-input v-model="hospdata.hospitalPhone" placeholder="请输入……" />
                </el-form-item>
                <el-form-item label="医院介绍">
                    <!-- 富文本工具栏 -->
                    <div style="border: 1px solid #ccc; border-radius: 4px;">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="'default'" />
                        <Editor style="height: 500px;" v-model="hospdata.intro" :defaultConfig="editorConfig"
                            :mode="'default'" @onCreated="handleCreated" @onChange="handleEditorChange" />
                    </div>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="">提交</el-button>
                    <el-button>取消</el-button>
                </el-form-item>
            </el-form>
        </header>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import router from '@/router'
import { Read, Write } from '@/Http/Axios'
import { useCounterStore } from '@/stores/counter'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { onBeforeUnmount, shallowRef } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const store = useCounterStore()




// 图片预览
const imageUrl = ref('')

// ✅ 修正：只保存图片 URL 字符串
const handleAvatarSuccess = (response: any) => {
    // 假设后端返回 { url: "http://.../xxx.jpg" }
    if (response && response.url) {
        hospdata.hospitalImg = response.url
    } else {
        // 如果直接返回字符串（如某些 mock 接口）
        hospdata.hospitalImg = response
    }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // 你可以暂时注释掉校验，先确保流程通
    return true
}


// 科室 transfer 数据
interface Option {
    key: number
    label: string
}

const data = ref<Option[]>([])
const loading = ref(false) // ✅ 正确定义 loading

const loadDepartments = async () => {
    loading.value = true
    try {
        const res = await Read.get("/SelectShow")
        if (Array.isArray(res.data.data)) {
            data.value = res.data.data.map((item: { departmentId: any; name: any }) => ({
                key: item.departmentId,
                label: item.name
            }))
        }
    } catch (error) {
        ElMessage.error('获取科室数据失败')
    } finally {
        loading.value = false
    }
}

// 返回
const set = () => {
    router.push('/HospitalShowView')
}

const hospdata = reactive(
    {
        "hospitalId": 7,
        "name": "解放军总医院",
        "hospitalImg": "http://localhost:5047/carousimg/2.webp",
        "isHospital": true,
        "hospitalCount": 2035,
        "hospitalCountTow": 302,
        "hospitalAdd": null,
        "hospitalAddTow": "沈阳市",
        "hospitalPhone": "辽北",
        "departments": [],
        "intro": "",
        "createName": "阿莱",
        "createTime": "2025-11-03T11:04:05.462574",
        "isDeleted": false,
        "head": "三甲"
    }
)


const getHospital = async () => {
    var id = route.query.hospitalId
    Read.get("/QueryHospital", {
        params: {
            HospitalId: id
        }
    }).then(res => {
        hospdata.name = res.data.data.name
        hospdata.hospitalImg = res.data.data.hospitalImg
        hospdata.isHospital = res.data.data.isHospital
        hospdata.hospitalCount = res.data.data.hospitalCount
        hospdata.hospitalCountTow = res.data.data.hospitalCountTow
        hospdata.departments = res.data.data.departments
        hospdata.hospitalAddTow = res.data.data.hospitalAddTow
        hospdata.hospitalPhone = res.data.data.hospitalPhone
        hospdata.intro = res.data.data.intro
        hospdata.createName = res.data.data.createName
        hospdata.createTime = res.data.data.createTime
        hospdata.isDeleted = res.data.data.isDeleted
        hospdata.head = res.data.data.head
        hospdata.hospitalId = res.data.data.hospitalId
        hospdata.hospitalAdd = res.data.data.hospitalAdd


    })
}
//钩子函数
onMounted(() => {
    getHospital()
    loadDepartments()
})

// ===== 富文本编辑器 =====
const editorRef = shallowRef()
const valueHtml = ref('<p>请在此编辑表单内容...</p>')

const toolbarConfig = {}
const editorConfig = {
    placeholder: '请输入内容...'
}

const handleCreated = (editor: any) => {
    editorRef.value = editor
}

const handleEditorChange = (editor: { getHtml: () => string }) => {
    valueHtml.value = editor.getHtml()
}

onBeforeUnmount(() => {
    if (editorRef.value) editorRef.value.destroy()
})

</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
<style scoped>
.form-field {
    display: inline-block;
    background: #e3f2fd;
    border: 1px solid #2196f3;
    border-radius: 4px;
    padding: 0 6px;
    margin: 0 2px;
    color: #1976d2;
    font-size: 14px;
    line-height: 1.8;
    cursor: default;
    user-select: none;
}
</style>